{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [],
   "source": [
    "from torch import Tensor\n",
    "\n",
    "def _find_sorted_array_position(tensor: Tensor, values_tensor: Tensor) -> Tensor:\n",
    "    dim0, dim1 = tensor.shape\n",
    "    expanded_values_tensor = values_tensor.resize_((dim0, 1)).expand(dim0, dim1)\n",
    "    position_of_value = torch.sum((tensor > expanded_values_tensor).long(), 1)\n",
    "    return position_of_value.add(1)\n",
    "\n",
    "\n",
    "def mrr(preds: Tensor, targs: Tensor) -> Tensor:\n",
    "    \"\"\"\n",
    "    E.g.:\n",
    "    preds = torch.tensor([[0.2, 0.55, 0.25], [0.005, 0.005, 0.99]])\n",
    "    targs = torch.tensor([1, 2])\n",
    "    -> 1.0\n",
    "    \"\"\"\n",
    "    pred_values = preds.gather(1, targs.view(-1, 1))\n",
    "    guessed_positions = _find_sorted_array_position(preds, pred_values).float()\n",
    "    reciprocal = torch.reciprocal(guessed_positions)\n",
    "    return torch.mean(reciprocal)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [],
   "source": [
    "import unittest\n",
    "\n",
    "\n",
    "class MrrTest(unittest.TestCase):\n",
    "    def test_mrr_1(self):\n",
    "        preds = torch.tensor([[0.2, 0.55, 0.25], [0.005, 0.005, 0.99]])\n",
    "        targs = torch.tensor([1, 2])\n",
    "\n",
    "        actual = mrr(preds, targs)\n",
    "        expected = 1.0\n",
    "        self.assertAlmostEqual(expected, actual.item())\n",
    "        \n",
    "    def test_mrr_simple(self):\n",
    "        preds = torch.tensor([[0.2, 0.55, 0.25], [0.006, 0.004, 0.99]])\n",
    "        targs = torch.tensor([0, 0])\n",
    "\n",
    "        actual = mrr(preds, targs)\n",
    "        expected = 0.41666668653\n",
    "        self.assertAlmostEqual(expected, actual.item())\n",
    "        \n",
    "MrrTest().test_mrr_1()\n",
    "MrrTest().test_mrr_simple()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from fastai.metrics import accuracy"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "metrics",
   "language": "python",
   "name": "metrics"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
